using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 管理任务面板的 UI
/// </summary>
public class QuestUI : Singleton<QuestUI>
{
    [Header("Reward")]
    public RectTransform rewardTransform;
    public ItemUI rewardItemPrefab;
    [Header("Base Elements")]
    public GameObject questPanel;
    public ItemToolTip itemToolTip;
    private bool isOpen;

    /// <summary>
    /// 左侧各种任务选项的父级物体
    /// </summary>
    [Header("Quest Name")]
    public RectTransform questListRectTransform;
    /// <summary>
    /// 任务选项的预设
    /// </summary>
    public QuestNameBtn questNameBtnPrefab;
    /// <summary>
    /// 任务详情描述
    /// </summary>
    [Header("Text Content")]
    public Text questContentText;
    [Header("Require")]
    public RectTransform requireBox;
    public QuestRequireText requireTextPrefab;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Q))
        {
            isOpen = !isOpen;
            questPanel.SetActive(isOpen);
            questContentText.text = string.Empty;
            // 显示左侧列表，包含所有的任务名称按钮
            SetupQuestList();
            // 关闭任务面板的同时，关闭 itemToolTip
            if (!isOpen)
            {
                itemToolTip.gameObject.SetActive(false);
            }
        }
    }
    public void SetupQuestList()
    {
        // 清空原有内容
        foreach (Transform item in questListRectTransform)
        {
            Destroy(item.gameObject);
        }
        foreach (Transform item in rewardTransform)
        {
            Destroy(item.gameObject);
        }
        foreach (Transform item in requireBox)
        {
            Destroy(item.gameObject);
        }

        foreach (var task in QuestManager.Instance.tasks)
        {
            var questNameBtn = Instantiate(questNameBtnPrefab, questListRectTransform);
            // 更新任务选项按钮
            questNameBtn.SetupNameText(task.questData);
            // 更新任务详情
            questNameBtn.questContentText = questContentText;
        }
    }
    public void SetupRequireTextList(QuestData_SO questData)
    {
        // 清除旧数据
        foreach (Transform item in requireBox)
        {
            Destroy(item.gameObject);
        }

        foreach (QuestData_SO.QuestRequire require in questData.questRequires)
        {
            var q = Instantiate(requireTextPrefab, requireBox);
            // 更新任务需求文本
            if (questData.questState == QuestState.Finish)
            {
                // 完成任务需求，文本变为灰色
                q.Setup(require.name);
            }
            else
            {
                // 初始化任务需求文本
                q.Setup(require);
            }
        }
    }
    public void SetupRewardItem(ItemData_SO itemData, int amount)
    {
        var item = Instantiate(rewardItemPrefab, rewardTransform);
        item.Setup(itemData, amount);
    }
}
